<?php

namespace app\supplier\model\chat;

use app\common\model\plus\chat\Chat as ChatModel;
use app\supplier\model\supplier\Supplier as SupplierModel;

/**
 * 客服消息模型类
 */
class Chat extends ChatModel
{

    /**
     * 隐藏字段
     */
    protected $hidden = [
        'app_id',
        'identify',
        'status',
        'update_time'
    ];

    //消息列表
    public function getList($user, $data)
    {
        $model = new ChatRelation();
        if ($data['nickName']) {
            $model = $model->where('ju.nickName', 'like', '%' . $data['nickName'] . '%');
        }
        $list = $model->alias('u')
            ->where(['u.user_id' => $user['user_id']])
            ->join('xxzshop_user ju', 'ju.user_id=u.user_id')
            ->field('ju.user_id,nickName,avatarUrl,u.create_time')
            ->paginate($data, false, ['query' => \request()->request()
            ]);
        foreach ($list as $key => &$value) {
            //最后对话时间
            $identify = $this->getIdentify($value['user_id'], $user['user_id']);
            $messageInfo = $this->where('identify', '=', $identify)->field('create_time,content,type')->order('chat_id desc')->find();
            $value['lasttime'] = $messageInfo['create_time'];
            $value['newMessage'] = $messageInfo;
        }
        return $list;
    }

    //获取聊天信息
    public function getMessage($data, $user)
    {
        $identify = $this->getIdentify($user['user_id'], $data['user_id']);
        $where['identify'] = $identify;
        $list = $this->where($where)->with(['user'])
            ->order('chat_id desc')
            ->paginate($data, false, ['query' => \request()->request()
            ]);
        foreach ($list as $key => $value) {
            if ($user['user_id'] == $value['user_id']) {
                $supplierInfo = SupplierModel::where('user_id', '=', $value['user_id'])->with(['logo'])->field('name,logo_id,shop_supplier_id')->find();
                if ($supplierInfo['logo']) {
                    $value['user']['avatarUrl'] = $supplierInfo['logo']['file_path'];
                }
                $value['user']['nickName'] = $supplierInfo['name'];
            }
        }
        return $list;
    }

    //获取消息条数
    public function mCount($user)
    {
        $num = 0;
        if ($user) {
            $where[] = ['user_id', '<>', $user['user_id']];
            $where[] = ['status', '=', 0];
            $where[] = ['identify', 'like', '%' . $user['user_id'] . '%'];
            $num = $this->where($where)->count();
        }
        return $num;
    }
}
